package dhm.com.hpx.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import java.lang.reflect.Method;

import dhm.com.hpx.App;
import dhm.com.hpx.utils.wifi.NetBroadcastReceiver;
import dhm.com.hpx.utils.wifi.NetUtil;

public abstract class BaseActivity extends AppCompatActivity implements NetBroadcastReceiver.NetEvent {


    public NetBroadcastReceiver netBroadcastReceiver;
    public static NetBroadcastReceiver.NetEvent event;
    private int netMobile;

    /**
     * 记录处于前台的Activity
     */
    private static BaseActivity mForegroundActivity = null;
    protected Bundle savedInstanceState;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int layoutId = getLayout();
        setContentView(layoutId);

        this.savedInstanceState = savedInstanceState;

        Window window = getWindow();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        // 鐘舵€佹爮锛堜互涓婂嚑琛屼唬鐮佸繀椤伙紝鍙傝€僺etStatusBarColor|setNavigationBarColor鏂规硶婧愮爜锛?
        getWindow().setStatusBarColor(Color.WHITE);
        //鐘舵€佹爮涓殑鏂囧瓧棰滆壊鍜屽浘鏍囬鑹诧紝闇€瑕乤ndroid绯荤粺6.0浠ヤ笂锛岃€屼笖鐩墠鍙湁涓€绉嶅彲浠ヤ慨鏀癸紙涓€绉嶆槸娣辫壊锛屼竴绉嶆槸娴呰壊鍗崇櫧鑹诧級
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //淇敼涓烘繁鑹诧紝鍥犱负鎴戜滑鎶婄姸鎬佹爮鐨勮儗鏅壊淇敼涓轰富棰樿壊鐧借壊锛岄粯璁ょ殑鏂囧瓧鍙婂浘鏍囬鑹蹭负鐧借壊锛屽鑷寸湅涓嶅埌浜嗐€?
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(uiOptions);
        }
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        decorView.setSystemUiVisibility(uiOptions);

//        getWindow().setNavigationBarColor(Color.parseColor("#a1a3a6"));
        getWindow().setNavigationBarColor(Color.BLACK);
        initView();
        initData();

        isNetworkConnect(this);

    }

    protected abstract int getLayout();

    protected abstract void initView();

    protected abstract void initData();

    //动态注册权限
    public void stateNetWork() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //权限没有获得
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_APN_SETTINGS) != PackageManager.PERMISSION_GRANTED) {
                // 没有获得授权，申请授权
                ActivityCompat.requestPermissions((Activity) this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.INTERNET, Manifest.permission.CAMERA, Manifest.permission.WRITE_APN_SETTINGS}, 100);
            }
        }
    }


    @Override
    public void onNetChange(int netMobile) {
        App.NET_STATUS = netMobile;
        if (netMobile == 1) {
//            Toast.makeText(this, "无线网络", Toast.LENGTH_SHORT).show();
        } else if (netMobile == 0) {
            Toast.makeText(this, "移动网络", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "没有连接网络,请连接网络", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermission = false;
        if (requestCode == 100) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermission = true;
                }
            }
        }
    }

    public void exit() {    //将所有的Activity全部销毁
        finish();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mForegroundActivity = this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netBroadcastReceiver);
    }

    /**
     * 获取当前处于前台的activity
     */
    public static BaseActivity getForegroundActivity() {
        return mForegroundActivity;
    }

    /**
     * 判断是否存在虚拟按键
     *
     * @return
     */
    public boolean checkDeviceHasNavigationBar() {
        boolean hasNavigationBar = false;
        Resources rs = getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class<?> systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }


    private void isNetworkConnect(Context context) {
        event = this;
        //实例化IntentFilter对象
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        netBroadcastReceiver = new NetBroadcastReceiver();
        registerReceiver(netBroadcastReceiver, filter);
    }


    public boolean inspectNet() {
        this.netMobile = NetUtil.getNetWorkState(BaseActivity.this);
        return isNetConnect();
    }

    /**
     * 判断有无网络 。
     *
     * @return true 有网, false 没有网络.
     */
    public boolean isNetConnect() {
        if (netMobile == 1) {
            return true;
        } else if (netMobile == 0) {
            return true;
        } else if (netMobile == -1) {
            return false;

        }
        return false;
    }

}
